/**
 * @author chentl
 * @version V1.0
 * @Project leisurely
 * @Title TimeServerHandler.java
 * @Description 时间服务器
 * @Package com.echo.ioex.io.server.handler
 * @date 2020/9/15 1:07 下午
 * @Copyright: 陈泰来の学习档案 .
 */
package com.echo.ioex.bio.server.handler;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;
import java.util.Date;


@Slf4j
public class TimeServerHandler implements Runnable {

    private Socket socket;

    public TimeServerHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            //新建输入输出流
            in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            out = new PrintWriter(this.socket.getOutputStream(), true);
            String currentTime = null;
            String body = null;

            while (true) {
                //无限阅读 直到读完
                body = in.readLine();
                if (body == null) break;
                log.info("Server 收到指令: " + body);
                currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER";
                //输出结果
                out.println("当前时间戳：" + currentTime);
                log.info("已将当前时间戳{} 返回: ", currentTime);
            }

        } catch (Exception e) {
            //异常时
            //关闭输入流
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }

            //关闭输出流
            if (out != null) {
                out.close();
                out = null;
            }

            //释放socket句柄资源
            if (this.socket != null) {
                try {
                    this.socket.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                } finally {
                    this.socket = null;
                }
            }

        }
    }
}
